<template>
	<view class="cloud-file flex flex-sub align-center">
		<block v-if="number == 1">
			<text class="flex-sub text-gray">{{val?val.name:placeholder}}</text>
			<button type="primary" class="uni-button margin-left-sm" @click="upload()">上传文件</button>
			<button v-if="download && val" type="default" class="uni-button margin-left-sm"
				@click="downloadFile(val.path)">下载</button>
		</block>
	</view>
</template>

<script>
	export default {
		name: 'cloud-file',
		data() {
			return {
				val: null,
				srcList: [],
			};
		},
		props: {
			name: {
				type: String,
				default: 'image'
			},
			title: {
				type: String,
				default: ''
			},
			placeholder: {
				type: [String, Number],
				default: '请选择文件'
			},
			value: [Object, Array],
			number: {
				type: Number,
				default: 1
			},
			extension: {
				type: Array,
				default: () => ['.docs', '.doc']
			},
			download: {
				type: Boolean,
				default: false
			}
		},
		watch: {
			value(newVal, oldVal) {
				console.log("watch value", newVal)
				if (typeof newVal == "undefined") {
					return;
				}
				if (this.number == 1) {
					this.val = newVal
				} else {
					this.srcList = newVal
				}
				if (this.formItem) {
					this.formItem.setValue(newVal)
				}
			}
		},
		created() {
			console.log(typeof this.value)
			if (this.number == 1) {
				this.val = this.value
			} else {
				this.srcList = this.value
			}
			//this.val = this.value
			this.form = this.getForm('uniForms')
			this.formItem = this.getForm('uniFormsItem')
			if (this.formItem) {
				if (this.formItem.name) {
					this.rename = this.formItem.name
					this.form.inputChildrens.push(this)
				}
			}

		},
		methods: {
			/**
			 * 初始化变量值
			 */
			init() {

			},
			/**
			 * 获取父元素实例
			 */
			getForm(name = 'uniForms') {
				let parent = this.$parent;
				let parentName = parent.$options.name;
				while (parentName !== name) {
					parent = parent.$parent;
					if (!parent) return false;
					parentName = parent.$options.name;
				}
				return parent;
			},
			uploadCallback(srcs) {
				if (this.number == 1) {
					this.val = srcs[0]
					this.$emit('input', this.val);
				} else {
					this.srcList = this.srcList.concat(srcs)
					this.$emit('input', this.srcList);
				}

			},
			del(index) {
				this.srcList.splice(index, 1)
			},
			downloadFile(url) {
				uni.downloadFile({
					url
				})
			},
			upload() {
				let dt = new Date();
				let tempFiles = [];
				uni.chooseFile({
					count: this.number - this.srcList.length, //默认100
					extension: this.extension,
					success: (res) => {
						console.log(res)
						if (res.tempFilePaths.length == 0) {
							console.log("文件没选择到")
							return;
						}
						console.log(JSON.stringify(res.tempFilePaths));
						tempFiles = res.tempFiles;
						let paths = [];
						console.log(res)
						let promises = [];
						uni.showLoading({
							title: "文件上传中"
						})
						//循环上传
						res.tempFilePaths.map((filePath, index) => {
							let names = ["jpg"];
							console.log(res.tempFiles[index])
							if (res.tempFiles[index].name && res.tempFiles[index].name.indexOf(".") >
								0) {
								names = res.tempFiles[index].name.split(".");
							} else if (res.tempFiles[index].path && res.tempFiles[index].path.indexOf(
									".") > 0) {
								names = res.tempFiles[index].path.split(".");
							}
							let fname = (Math.random() + '').substr(2) + "." + names[names.length - 1];
							let cpath = this.name + '/' + fname;
							console.log(cpath)
							let uploadPromise = cloudUploadFile(filePath, cpath, index);
							promises.push(uploadPromise)
						})
						Promise.all(promises).then(res => {
							console.log(res);
							uni.hideLoading();
							this.uploadCallback(res);
						});
					}
				});

				function cloudUploadFile(filePath, cpath, index) {
					let obj = {
						name: tempFiles[index].name,
						path: "",
						size: tempFiles[index].size,
						type: tempFiles[index].type,
						lastModified: tempFiles[index].lastModified,
					}
					return new Promise((resolve, reject) => {
						let result = uniCloud.uploadFile({
							filePath: filePath,
							cloudPath: cpath,
							onUploadProgress: pro => {},
							success: res => {
								console.log("cloudUploadFile", res)
								if (res.fileID.indexOf("cloud://") != -1) {
									//用这个转换一下，有一个隐藏的好处，可以等待文件发布到cdn，避免立即访问不到
									uniCloud.getTempFileURL({
										fileList: [res.fileID]
									}).then(res2 => {
										obj.path = res2.fileList[0].tempFileURL;
										resolve(obj);
									})
								} else {
									//延时返回，可以等待文件发布到cdn，避免立即访问不到
									setTimeout(() => {
										obj.path = res.fileID;
										resolve(obj);
									}, 200);
								}
							},
							fail: () => {
								reject(false);
							}
						});
					});
				};
			}
		}
	}
</script>

<style lang="scss">
	.cloud-file {
		max-width: 900rpx;
	}
</style>
